import React, {useEffect, useMemo, useState} from 'react'
import {Space, Button, Popconfirm, Modal, Form, Input, message} from 'antd'
import validator from 'validator'
import {ArrowUpOutlined} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import DriverModal from './DriverModal'
import SearchForm from '@/components/SearchForm'
import {ManagerColnums, PageType, OperationDriverType} from '../constant'
import Styles from './index.less'
import {modalApi} from '@/utils/modalReq'
import BatchUpload from '@/components/BatchUpload'
import {
	getFleetadminErrorListPage,
	getFleetadminImportData,
	getFleetAdmin,
	getFleetAdminList,
	addFleetAdmin,
	editFleetAdmin,
	deleteFleetAdmin,
	getFleetAdminId,
} from '@/service/customer/fleet'
import CustomTable from '@/components/Table'

interface ManagerInfoType {
	pageType: any
	fleetId: string
}

// eslint-disable-next-line no-shadow
enum OperationType {
	Add = 'add',
	Edit = 'edit',
	Review = 'review',
}

interface DataType {
	name: string
	phone: string
	reason: string
}

const operationMap: Record<OperationType, string> = {
	[OperationType.Add]: '添加',
	[OperationType.Edit]: '编辑',
	[OperationType.Review]: '查看',
}

function ManagerInfo({pageType, fleetId}: ManagerInfoType) {
	const [managerForm] = Form.useForm()
	const [loading, setLoading] = useState(false)
	const [total, setTotal] = useState(0)
	const [dataList, setDataList] = useState<any[]>([])
	const [addModalVisivle, setAddModalVisivle] = useState(false)
	const [saveLoading, setSaveLoading] = useState(false)
	const [driverModalVisivle, setdriverModalVisivle] = useState(false)
	const [operationType, setOperationType] = useState(OperationType.Add)
	const [operationDriver, setOperationDriver] = useState(
		OperationDriverType.Add,
	)
	const [countObj, setCountObj] = useState({
		driver: 0,
		admin: 0,
	})
	// const [fleetAdminId, setFleetAdminId] = useState('')
	const [fleetAdminRecord, setFleetAdminRecord] = useState<any>({})
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const [searchData, setSearchData] = useState<any>({})
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const FormItems: any[] = useMemo(
		() => [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						key: 'name',
						name: 'name',
						label: '司管员名称',
					},
					{
						type: 'input',
						key: 'id',
						name: 'id',
						label: '司管员id',
					},
					{},
				],
			},
		],
		[],
	)

	// 添加司管员
	const onAdd = async () => {
		setOperationType(OperationType.Add)
		setAddModalVisivle(true)
		managerForm.resetFields()

		const data = await getFleetAdminId()
		if (data.code === 0) {
			// setFleetAdminId(data.data)
			managerForm.setFieldValue('id', data.data)
		}
	}

	// 查看司官员
	const onReview = (record: Record<string, string>) => {
		setOperationType(OperationType.Review)
		setAddModalVisivle(true)
		managerForm.setFieldsValue({
			id: record.id,
			name: record.name,
			phone: record.phone,
		})
	}

	// 编辑司官员
	const onEdit = (record: Record<string, string>) => {
		setOperationType(OperationType.Edit)
		setAddModalVisivle(true)
		managerForm.setFieldsValue({
			id: record.id,
			name: record.name,
			phone: record.phone,
		})
	}

	// 司机迁移
	const onTransfer = (record: Record<string, string>) => {
		setOperationDriver(OperationDriverType.Transfer)
		setdriverModalVisivle(true)
		setFleetAdminRecord(record)
	}
	const getData = async () => {
		setLoading(true)
		const obj = {
			fleetId,
			...params,
			...searchData,
		}
		const data = await getFleetAdminList(obj).catch(() => setLoading(false))
		if (data.code === 0) {
			setDataList(data.data.records)
			setTotal(data.data.total)
		}
		setLoading(false)
	}

	const getFleetAdminData = async () => {
		const data = await getFleetAdmin({fleetId})
		if (data.code === 0) {
			setCountObj(data.data)
		}
	}

	// 删除司机
	const onDelete = async (id: string) => {
		const data = await deleteFleetAdmin({id})
		if (data.code === 0) {
			message.success('删除成功')
			// if (total % pagination.pageSize === 1 && total > 10) {
			//   setPagination({
			//     ...pagination,
			//     current: pagination.current - 1,
			//   });
			// } else {
			getData()
			// }
			getFleetAdminData()
		} else {
			message.error('删除失败')
		}
	}

	// 添加司管员司机
	const onAddDriver = async (record: Record<string, string>) => {
		setOperationDriver(OperationDriverType.Add)
		setdriverModalVisivle(true)
		setFleetAdminRecord(record)
	}

	const onSave = async () => {
		const formData = await managerForm.validateFields()

		if (operationType === OperationType.Add) {
			setSaveLoading(true)
			const data = await addFleetAdmin({
				fleetId,
				...formData,
			}).catch(() => setSaveLoading(false))
			if (data.code === 0) {
				message.success('新增成功')
				setAddModalVisivle(false)
				setSaveLoading(false)
				getData()
				getFleetAdminData()
			} else {
				setSaveLoading(false)
			}
		} else if (operationType === OperationType.Edit) {
			setSaveLoading(true)
			const data = await editFleetAdmin({
				fleetId,
				...formData,
			}).catch(() => setSaveLoading(false))
			if (data.code === 0) {
				message.success('编辑成功')
				setAddModalVisivle(false)
				setSaveLoading(false)
				// eslint-disable-next-line no-use-before-define
				getData()
			} else {
				setSaveLoading(false)
			}
		} else {
			setAddModalVisivle(false)
		}
	}
	const getColnums: any[] = useMemo(() => {
		const col: any[] = [...ManagerColnums]
		if (pageType !== PageType.Detail) {
			col.push({
				title: '操作',
				dataIndex: 'operation',
				align: 'center',
				width: 200,
				render: (key: string, record: Record<string, string>) => (
					<Space size={12}>
						<Button type="link" onClick={() => onReview(record)}>
							查看
						</Button>
						<Button type="link" onClick={() => onEdit(record)}>
							编辑
						</Button>
						<Button type="link" onClick={() => onTransfer(record)}>
							司机迁移
						</Button>
						<Button type="link" onClick={() => onAddDriver(record)}>
							添加司机
						</Button>
						<Popconfirm
							placement="topLeft"
							title={
								Number(record.driverCount) > 0
									? `司管员下还有${record.driverCount}名司机，请先将司机迁移，再点击确定按钮`
									: '确定删除该数据吗？'
							}
							onConfirm={() => onDelete(record.id)}
							okText="确定"
							cancelText="取消"
							okButtonProps={{
								disabled: Number(record.driverCount) > 0,
							}}>
							<Button type="link">删除</Button>
						</Popconfirm>
					</Space>
				),
			})
		}
		return col
	}, [pageType, dataList, operationType, total, params])

	useEffect(() => {
		if (!fleetId) return
		getFleetAdminData()
	}, [fleetId])
	useEffect(() => {
		if (fleetId) {
			getData()
		}
	}, [fleetId, params])

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '司管员名称',
			dataIndex: 'name',
			align: 'center',
		},
		{
			title: '司管员手机号',
			dataIndex: 'phone',
			align: 'center',
		},
		{
			title: '失败原因',
			dataIndex: 'reason',
			align: 'center',
		},
	]

	return (
		<div className={Styles.managerInfo}>
			<div className={Styles.titleBox}>
				<div className={Styles.title}>司管员信息</div>
				<div className={Styles.countBox}>
					(
					<div className={Styles.item}>
						共{countObj.admin || 0}个司管员
					</div>
					<div className={Styles.item}>
						司机总数{countObj.driver || 0}人
					</div>
					)
				</div>
			</div>
			<div className={Styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '90px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={FormItems}
					onReset={() => {
						setSearchData({})
						setParams({
							current: 1,
							size: 10,
						})
					}}
					onFinish={(value) => {
						setSearchData(value)
						setParams({
							current: 1,
							size: 10,
						})
					}}
				/>
			</div>
			<div className={Styles.content}>
				{pageType !== PageType.Detail && (
					<div className={Styles.btnList}>
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => onAdd()}>
							添加司管员
						</Button>
						<Button
							icon={<ArrowUpOutlined />}
							className={Styles.warning}
							ghost
							size="small"
							onClick={() => setIsUploadModalOpen(true)}>
							导入
						</Button>
					</div>
				)}
				<CustomTable
					params={params}
					columns={getColnums}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					loading={loading}
					dataSource={dataList}
				/>
			</div>

			<Modal
				title={`${operationMap[operationType]}司管员`}
				open={addModalVisivle}
				onCancel={() => {
					setAddModalVisivle(false)
				}}
				width={500}
				onOk={onSave}
				okButtonProps={{loading: saveLoading}}>
				<Form
					layout="horizontal"
					labelCol={{flex: '140px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					name="PersonalInformationFom"
					form={managerForm}
					disabled={operationType === OperationType.Review}>
					<Form.Item label="司管员id" name="id">
						<Input disabled />
					</Form.Item>
					<Form.Item
						label="司管员姓名"
						name="name"
						rules={[{required: true}]}>
						<Input placeholder="请输入" />
					</Form.Item>
					<Form.Item
						label="司管员联系方式"
						name="phone"
						required
						rules={[
							{required: true},
							{
								validator(rule, value) {
									if (
										value === undefined ||
										value.length === 0
									) {
										return Promise.resolve('')
									}
									return validator.isMobilePhone(value)
										? Promise.resolve('')
										: Promise.reject(
												new Error('请输入正确的手机号'),
										  )
								},
							},
						]}>
						<Input placeholder="请输入" />
					</Form.Item>
				</Form>
			</Modal>

			<DriverModal
				driverModalVisivle={driverModalVisivle}
				setdriverModalVisivle={setdriverModalVisivle}
				fleetAdminRecord={fleetAdminRecord}
				callBack={() => {
					getFleetAdminData()
					getData()
				}}
				operationDriver={operationDriver}
				fleetId={fleetId}
			/>
			<BatchUpload
				id={fleetId}
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getFleetadminImportData}
				onTableList={getFleetadminErrorListPage}
				getListData={getData}
				downloadUrl="customer/司管员导入.xlsx"
				uploadFileUrl={`${modalApi.customer}/fleetadmin/import/check`}
				columns={errorColumns}
				sourceId={12}
				templateType="司管员导入"
			/>
		</div>
	)
}

export default ManagerInfo
